package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.MenuMapper;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    MenuMapper menuMapper;


    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);
    }

    public void saveOrUpdate(Role record) {
        if (record.getId() == null) {
            roleMapper.insert(record);
            //关联关系
            List<Permission> permissions = record.getPermissions();
            for (Permission permission : permissions) {
                roleMapper.insertRelation(record.getId(),permission.getId());
            }

            //关联关系
            List<Menu> menus = record.getMenus();
            for (Menu menu : menus) {
                roleMapper.insertMenuRelation(record.getId(),menu.getId());
            }
        } else {
            roleMapper.updateByPrimaryKey(record);
            //删除关系
            roleMapper.deleteRelation(record.getId());

            //关联关系
            List<Permission> permissions = record.getPermissions();
            for (Permission permission : permissions) {
                roleMapper.insertRelation(record.getId(),permission.getId());
            }

            //删除关系
            roleMapper.deleteMenuRelation(record.getId());

            //关联关系
            List<Menu> menus = record.getMenus();
            for (Menu menu : menus) {
                roleMapper.insertMenuRelation(record.getId(),menu.getId());
            }

        }
    }

    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }



    public List<Role> getAll() {
        return roleMapper.selectAll();
    }

    public List<Long> getMenuIdByRoleId(Long roleId) {
        return menuMapper.getMenuIdByRoleId(roleId);
    }

    public List<String> selectByEmployeeId(Long id) {
        return roleMapper.selectByEmployeeId(id);
    }
}
